import React, { useState } from 'react'
import Head from '../component/Head'
import axios from 'axios'
import { Toast } from 'react-vant';
import {useNavigate} from 'react-router-dom'
export default function Up_password() {
    const navigate=useNavigate()
    const [password, setpassword] = useState('')
    const [newpassword, setnewpassword] = useState('')
    const [newpassword2, setnewpassword2] = useState('')

    const update = async () => {
        if (newpassword != newpassword2) {
            Toast.fail('两次输入的密码不一致')
            return
        }
        if (password.trim().length === 0 || newpassword.trim().length === 0 || newpassword2.trim().length === 0) {
            Toast.fail('请输入完整信息')
            return
        }
        if(password!==JSON.parse(sessionStorage.user).password){
            Toast.fail('旧密码错误')
            return
        }
        let {_id}=JSON.parse(sessionStorage.user)
        let {data}=await axios.get('http://localhost:3000/updatepassword',{
            params:{
                newpassword:newpassword,
                id:_id
            }
        })
        console.log(data);
        if(data.code===200){
            sessionStorage.removeItem('userid')
            sessionStorage.removeItem('token')
            sessionStorage.removeItem('user')
            Toast.success(data.msg)
            navigate('/login')
        }
    }
    return (
        <div>
            <Head titleName='修改密码'></Head>
            <div style={{ padding: '20px', height: '50px' }}>
                <div style={{ width: '100%', borderBottom: '2px solid #F2F2F2', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <input value={password} onChange={(e) => { setpassword(e.target.value) }} style={{ width: '60%', height: '50px', border: 'none' }} placeholder='请输入旧密码' type="text" />
                </div>
                <div style={{ width: '100%', borderBottom: '2px solid #F2F2F2', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <input value={newpassword} onChange={(e) => { setnewpassword(e.target.value) }} style={{ width: '60%', height: '50px', border: 'none' }} placeholder='请输入新密码(不少于6位)' type="text" />
                </div>
                <div style={{ width: '100%', borderBottom: '2px solid #F2F2F2', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <input value={newpassword2} onChange={(e) => { setnewpassword2(e.target.value) }} style={{ width: '60%', height: '50px', border: 'none' }} placeholder='请再次输入新密码' type="text" />
                </div>
            </div>
            <div style={{ marginTop: '120px', padding: '0px 75px' }}>
                <div onClick={() => { update() }} style={{ backgroundColor: '#C7C9FC', height: '50px', textAlign: 'center', lineHeight: '50px', color: 'white' }}>确认修改</div>
            </div>
        </div>
    )
}
